<?php
declare (strict_types=1);

namespace app\store\model\student;

use app\api\model\Setting as SettingModel;
use app\common\model\student\Sign as SignModel;
use app\store\model\job\Job;
use think\db\exception\DbException;
use think\facade\Db;
use think\Paginator;
use app\store\model\UploadFile as UploadFileModel;
use PhpOffice\PhpSpreadsheet\IOFactory;

class Sign extends SignModel
{
    /**
     * 获取列表
     * @param array $param
     * @return Paginator
     * @throws DbException
     */
    public function getList($param = [])
    {
        // 查询模型
        $query = $this->getNewQuery();
        // 查询参数
        $filter = $this->getQueryFilter($param);

        $order = [
            'a.student_sign_id' => 'desc',
        ];

        if (!empty($param['create_time']) && is_array($param['create_time'])) {
            $times = between_time2($param['create_time']);
            $filter[] = ['a.create_time', '>=', $times['start_time']];
            $filter[] = ['a.create_time', '<', $times['end_time']];
        } else if (!empty($param['create_time'])) {
            $order['a.create_time'] = $param['create_time'];
        }

        if (!empty($param['report_time']) && is_array($param['report_time'])) {
            $times = between_time2($param['report_time']);
            $filter[] = ['a.report_time', '>=', $times['start_time']];
            $filter[] = ['a.report_time', '<', $times['end_time']];
        } else if (!empty($param['create_time'])) {
            $order['a.report_time'] = $param['report_time'];
        }

        if (!empty($param['registration_time']) && is_array($param['registration_time'])) {
            $times = between_time($param['registration_time']);
            $filter[] = ['a.registration_time', '>=', $times['start_time']];
            $filter[] = ['a.registration_time', '<', $times['end_time'] + 86400];
        }


        // 查询列表记录
        $list = $query->alias('a')
            ->with(['job', 'store_user'])
            ->field('a.student_sign_id,a.student_user_id,a.job_id,a.store_user_id,a.job_level,a.channel_name,a.status,a.report,a.report_time,a.registration_time,a.create_time,a.learning_duration,a.contact,a.remark,b.full_name,b.id_card')
            ->join('student_user b', 'a.student_user_id=b.student_user_id')
            ->where($filter)
            ->where([
                'a.is_delete' => 0,
                'b.is_delete' => 0,
            ])
            ->order($order)
            ->paginate($param['pageSize'] ?? 10);

        return $list;
    }


    public function getQueryFilter($param)
    {
        $params = $this->setQueryDefaultValue($param, [
            'full_name' => '',
            'id_card' => '',
            'job_name' => '',
            'channel_name' => '',
            'job_level' => '',
            'status' => -1,
            'report' => -1,
            'store_user_id' => 0,
        ]);

        $filter = [];
        !empty($params['full_name']) && $filter[] = ["full_name", "like", "%{$params['full_name']}%"];
        !empty($params['channel_name']) && $filter[] = ["channel_name", "like", "%{$params['channel_name']}%"];
        !empty($params['id_card']) && $filter[] = ["id_card", "like", "%{$params['id_card']}%"];
        if (!empty($params['job_name'])) {
            $job = (new Job())->where([
                'job_name' => $params['job_name'],
                'is_delete' => 0
            ])->find();
            $filter[] = ['job_id', '=', $job->job_id ?? ''];
        }
        !empty($params['job_level']) && $filter[] = ["job_level", "=", $params['job_level']];
        $params['status'] > -1 && $filter[] = ['status', '=', $params['status']];
        $params['report'] > -1 && $filter[] = ['report', '=', $params['report']];
        $params['store_user_id'] && $filter[] = ['store_user_id', 'in', $params['store_user_id']];
        return $filter;
    }

    public function saveList($questionnaire_id, $data)
    {
        $saveList = [];
        $this->where(['questionnaire_id' => $questionnaire_id])->save(['is_delete' => 1]);
        foreach ($data as $key => $item) {
            if (!empty($item['topic_id'])) {
                $this->where(['topic_id' => $item['topic_id']])->save([
                    'sort' => $key,
                    'questionnaire_id' => $questionnaire_id,
                    'title' => $item['title'],
                    'topic_type' => $item['topic_type'],
                    'scoring_method' => $item['scoring_method'],
                    'fraction' => $item['fraction'],
                    'items' => json_encode($item['items'], 320),
                    'correct_answer' => implode(',', $item['correct_answer']),
                    'is_delete' => 0
                ]);
            } else {
                $saveList[] = [
                    'sort' => $key,
                    'questionnaire_id' => $questionnaire_id,
                    'title' => $item['title'],
                    'topic_type' => $item['topic_type'],
                    'scoring_method' => $item['scoring_method'],
                    'fraction' => $item['fraction'],
                    'items' => json_encode($item['items'], 320),
                    'correct_answer' => implode(',', $item['correct_answer']),
                    'store_id' => self::$storeId,
                    'create_time' => time(),
                    'is_delete' => 0
                ];
            }
        }
        return $this->saveAll($saveList);
    }

    /**
     * 增加记录
     * @param array $data
     * @return bool
     */
    public function add($data, $store_user)
    {
        if (!empty($data['registration_time'])) {
            $data['registration_time'] = strtotime($data['registration_time']);
        }
        $data['store_user_id'] = $store_user['store_user_id'];
        $data['store_id'] = self::$storeId;
        return $this->save($data) ? $this->student_sign_id : false;
    }

    public function importExcelFile($file_id, $store_user)
    {
        $fileInfo = UploadFileModel::detail((int)$file_id);
        $filePath = ROOT_PATH() . '/public/uploads/' . $fileInfo->file_path;
        $spreadsheet = IOFactory::load($filePath);
        $list = $spreadsheet->getActiveSheet()->toArray();
        $error = "";
        $addData = [];
        foreach ($list as $index => $item) {
            if ($index > 0) {
                $data = [
                    'is_delete' => 0,
                    'registration_time' => time(),
                    'create_time' => time(),
                    'store_id' => self::$storeId,
                    'store_user_id' => $store_user['store_user_id']
                ];
                $user = [];
                $hanshu = $index + 1;
                // 姓名
                if ($item[1]) {
                    $user["full_name"] = trim((string)$item[1]);
                } else {
                    $error = "第{$hanshu}行错误：姓名不能为空！";
                    break;
                }
                // 身份证号码
                if (!$item[2] || !isIdCard((string)$item[2])) {
                    $error = "第{$hanshu}行错误：身份证号码为空/身份证号码无效！";
                    break;
                } else {
                    $user["id_card"] = trim((string)$item[2]);
                }

                $age = get_age2($user["id_card"]);
                if ($age < 18 || $age > 60) {
                    $error = "第{$hanshu}行错误：年龄未在18~60岁之间！";
                    break;
                }

                $studentUser = User::findUser($user["full_name"], $user["id_card"]);
                if (!$studentUser) {
                    $model = new User;
                    $model->save([
                        'full_name' => $user["full_name"],
                        'id_card' => $user["id_card"],
                        'is_delete' => 0,
                        'create_time' => time(),
                        'store_id' => self::$storeId,
                    ]);
                    $studentUser = $model;
                }
//var_dump($studentUser->student_user_id);
                $data['student_user_id'] = $studentUser->student_user_id;

                // 工种
                if (!$item[3]) {
                    $error = "第{$hanshu}行错误：岗位为空！";
                    break;
                } else {
                    $job_name = trim((string)$item[3]);
                    //查找工种
                    $job = (new Job())
                        ->where(['job_name' => $job_name, 'is_delete' => 0,])
                        ->find();
                    if (!$job) {
                        $error = "第{$hanshu}行错误：岗位【{$job_name}】信息不存在！";
                        break;
                    }

                    if ($job->status === 1) {
                        $error = "第{$hanshu}行错误：岗位【{$job_name}】已被停用！";
                        break;
                    }
                    $data["job_id"] = $job->job_id;
                }

                if (!$item[4]) {
                    $error = "第{$hanshu}行错误：岗位等级为空！";
                    break;
                } else {
                    $job_levels = [
                        '初级' => 'primary',
                        '中级' => 'intermediate',
                        '高级' => 'senior',
                        '--' => 'not',
                    ];
                    $job_level_name = trim((string)$item[4]);
                    if (empty($job_levels[$job_level_name])) {
                        $error = "第{$hanshu}行错误：【{$job_name}】岗位等级【{$job_level_name}】不在【初级，中级，高级，--】中！";
                        break;
                    }

                    if (empty($job[$job_levels[$job_level_name]])) {
                        $error = "第{$hanshu}行错误：【{$job_name}】岗位等级【{$job_level_name}】未启用，请联系管理员！";
                        break;
                    }

                    if (empty($job[$job_levels[$job_level_name] . '_questionnaire_id'])) {
                        $error = "第{$hanshu}行错误：【{$job_name}】岗位等级【{$job_level_name}】未绑定题库，请联系管理员！";
                        break;
                    }

                    $data['job_level'] = $job_levels[$job_level_name];
                    $data['questionnaire_id'] = $job[$job_levels[$job_level_name] . '_questionnaire_id'];
                }

                if (!$item[5]) {
                    $error = "第{$hanshu}行错误：渠道名称为空！";
                    break;
                } else {
                    $data["channel_name"] = trim((string)$item[5]);
                }

                if (!empty($item[6])) {
                    $data["remark"] = trim((string)$item[6]);
                } else {
                    $data["remark"] = '';
                }

                $student_user = $this->where([
                    'student_user_id' => $data['student_user_id'],
                    'job_id' => $data['job_id'],
                    'job_level' => $data['job_level'],
                    'is_delete' => 0
                ])->find();
                if ($student_user) {
                    $error = "第{$hanshu}行错误：【{$user["full_name"]}】【{$user["id_card"]}】【{$job_name}】【{$job_level_name}】已存在记录，请勿重复导入！";
                    break;
                }

                $addData[] = $data;
            }
        }
        if ($error) {
            $this->error = $error;
            return false;
        }
        return $this->insertAll($addData) ? count($addData) : false;
    }

    /**
     * 更新记录
     * @param array $data
     * @return bool
     */
    public function edit(array $data)
    {
        if (!empty($data['registration_time'])) {
            $data['registration_time'] = strtotime($data['registration_time']);
        }
        return $this->save($data);
    }

    /**
     * 软删除
     * @return false|int
     */
    public function setDelete()
    {
        return $this->save(['is_delete' => 1]);
    }

    public function reported($ids)
    {
        return $this->where($this->getPk(), 'in', $ids)->save(['report' => 1, 'report_time' => time()]);
    }

    public function generateClassHours($ids)
    {

        $values = SettingModel::getItem('examination');
        $compulsory_learning = !empty($values['compulsory_learning']) ? $values['compulsory_learning'] : 0;
        if (!$compulsory_learning) {
            return true;
        }
        return $this->where($this->getPk(), 'in', $ids)->update([
            'learning_duration' => Db::raw('FLOOR(' . $compulsory_learning . ' + RAND() * ' . ceil($compulsory_learning / 2 + 1) . ')')
        ]);
    }

}
